#include "contactlistwidget.h"
#include "ui_contactlistwidget.h"
#include "Views/contactlistitem.h"
#include "Views/contactnameitem.h"

ContactListWidget::ContactListWidget(QWidget *parent) :
    QWidget(parent),
    m_widget(nullptr),
    ui(new Ui::ContactListWidget)
{
    ui->setupUi(this);
    installEventFilter(this);
}

ContactListWidget::~ContactListWidget()
{
    delete ui;
}

void ContactListWidget::AddItem(Group *data)
{
    if (data->name() == "") {
        auto widget = new ContactNameItem;
        widget->item(data);
        auto item = new QListWidgetItem;
        QVariant var = QVariant::fromValue(data);
        item->setData(Qt::UserRole, var);
        item->setSizeHint(widget->size());
        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item, widget);
        //connect(widget, &ContactNameItem::)
    } else {
        auto widget = new ContactListItem;
        widget->item(data);
        auto item = new QListWidgetItem;
        QVariant var = QVariant::fromValue(data);
        item->setData(Qt::UserRole, var);
        item->setSizeHint(widget->size());
        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item, widget);
        connect(widget, &ContactListItem::selected, this, &ContactListWidget::onItemSelected);
    }
}

void ContactListWidget::onItemSelected(QWidget *item)
{
    if (m_widget != nullptr) {
        auto name = m_widget->objectName();
        if (name == "ContactListItem") {
            auto widget = this->getWidget<ContactListItem>(m_widget);
            widget->Checked(false);
            widget->Selected(false);
        }
    }
    m_widget = item;
    auto name = item->objectName();
    if (name == "ContactListItem") {
        auto widget = this->getWidget<ContactListItem>(item);
        widget->Checked(true);
        widget->Selected(true);
    }
}

template<class T>
T *ContactListWidget::getWidget(QWidget *item)
{
    return dynamic_cast<T*>(item);
}
